Iterables


Iterables are objects that can be iterated over, meaning you can loop through their elements. Common examples of iterables in JavaScript include arrays, strings, and sets.

1. Iterating Over Arrays

Arrays are one of the most common iterables in JavaScript:

const array = [1, 2, 3, 4, 5];
for (let value of array) {
    console.log(value);
}
// Outputs: 1 2 3 4 5

2. Iterating Over Strings

Strings are also iterables, allowing you to loop through each character:

const string = "Hello";
for (let char of string) {
    console.log(char);
}
// Outputs: H e l l o

3. Iterating Over Sets

Sets are collections of unique values and can be iterated over:

const set = new Set([1, 2, 3, 4, 5]);
for (let value of set) {
    console.log(value);
}
// Outputs: 1 2 3 4 5

4. Custom Iterables

You can create custom iterables by implementing the [Symbol.iterator] method:

const customIterable = {
    *Symbol.iterator {
        yield 1;
        yield 2;
        yield 3;
    }
};

for (let value of customIterable) {
    console.log(value);
}
// Outputs: 1 2 3

5. Using Iterators

Iterators are objects that provide a next() method, which returns the next item in the sequence:

const array = [1, 2, 3];
const iterator = arraySymbol.iterator;

console.log(iterator.next()); // Outputs: { value: 1, done: false }
console.log(iterator.next()); // Outputs: { value: 2, done: false }
console.log(iterator.next()); // Outputs: { value: 3, done: false }
console.log(iterator.next()); // Outputs: { value: undefined, done: true }

6. Iterating with for...of

The for...of loop is a convenient way to iterate over iterables:

const array = [1, 2, 3, 4, 5];
for (let value of array) {
    console.log(value);
}
// Outputs: 1 2 3 4 5